/**
 * 用户列表
 */
import React from 'react';
import styles from './index.less';
import { connect, connectMaster, history } from 'umi';
import { Button, Form, Space, Table, Modal, message, Select } from 'antd';
const { Option } = Select;
import { Subject } from 'rxjs-compat';
// import UserForm from './UserForm';
import { commonApi } from '@/network/api';
const {
  approvalSearch,
  approvalDel,
  APIDetail,
  approvalAgree,
  approvalReject,
} = commonApi;
import MsgBox from '../components/MsgBox';
import moment from 'moment';

import { getMasterCommonPkg } from '@/utils/masterData';
const {
  utils: {
    otherUtil: { authorityVerify },
  },
} = getMasterCommonPkg();
@connectMaster //接收主服务数据
@connect(({ UserList }) => ({
  UserList,
}))
export default class extends React.Component {
  state = {
    total: 0,
    pageSize: 10,
    pageNum: 1,
    businessType: '',
    status: '',
    dataList: [],
    dataMsg: {},
    boxtype: '',
    isVisable: false,
    title: '',
  };
  componentDidMount = async () => {
    this.eventInit();
    this.getList();
    // this.getAllRoleList();
  };
  eventInit = () => {
    this.searchChangeEvent = new Subject();
    //(防抖)
    this.searchChangeEvent.debounceTime(300).subscribe(data => {
      this.getList({});
    });
  };

  //获得所有角色
  getAllRoleList = async () => {
    var rs = await this.props.dispatch({
      type: 'UserList/getAllRoleList',
    });

    //失败
    if (!rs.success) {
      message.error('删除失败');
    }
    // 成功
    if (rs.success) {
      this.changeState({
        allRoleList: rs.data,
      });
    }
  };

  //获取角色列表
  getRoleList = async (params = {}) => {
    var reqData = {
      pageNum: 1,
      pageSize: 100000000,
      ...params,
    };

    var rs = await this.props.dispatch({
      type: 'UserList/getRoleList',
      payload: reqData,
    });
    // 成功
    if (rs.success) {
      this.changeState({
        roleList: rs.data.dataList,
      });
    }
  };

  // 获取用户列表
  getList = async (params = {}) => {
    const { pageNum, pageSize, status, businessType } = this.state;
    approvalSearch({
      pageNum,
      pageSize,
      businessType,
      status,
    }).then(res => {
      if (res.success) {
        const { pageNum, pageSize, total, dataList } = res.data;
        this.setState({
          pageNum: parseInt(pageNum),
          pageSize: parseInt(pageSize),
          total: parseInt(total),
          dataList,
        });
      }
      console.log(res, 8888888888);
    });
  };

  //删除用户
  deleteUser = id => {
    Modal.confirm({
      title: '你确定要删除吗?',
      content: '你确定要删除吗?',
      centered: true,
      onOk: async () => {
        // 走接口删除
        approvalDel({ id }).then(rs => {
          if (!rs.success) {
            message.error('删除失败');
          }
          // 成功
          if (rs.success) {
            let { pageNum, pageSize } = this.state;
            if (pageSize == 1 && pageNum > 1) {
              this.setState({
                pageNum: pageNum - 1,
              });
            }
            message.success('删除成功');
            //  更新列表
            this.getList();
          }
        });
      },
    });
  };

  //启用/禁用用户
  getUserEnabled = async (checked, id) => {
    var obj = {
      id: id,
      enabled: checked,
    };
    var rs = await this.props.dispatch({
      type: 'UserList/getUserEnabled',
      payload: obj,
    });

    //失败
    if (!rs.success) {
      message.error('操作失败');
    }
    // 成功
    if (rs.success) {
      message.success('操作成功');
      //  更新列表
      this.getList();
    }
  };

  //更新状态
  changeState = obj => {
    this.props.dispatch({
      type: 'UserList/setState',
      payload: obj,
    });
  };

  // 关闭盒子清空数据

  closeBox() {
    this.setState({
      dataMsg: {},
      boxtype: '',
      isVisable: false,
      title: '',
    });
  }

  // 接口提交 - 并刷新列表
  onSubmit(msg) {
    const { type, rejectReason, dataMsg } = msg;
    if (type == 1) {
      approvalAgree({ id: dataMsg.id }).then(res => {
        this.getList();
        this.setState({
          dataMsg: {},
          boxtype: '',
          isVisable: false,
          title: '',
        });
      });
    } else {
      approvalReject({
        applyId: dataMsg.id,
        rejectReason,
      }).then(res => {
        this.getList();
        this.setState({
          dataMsg: {},
          boxtype: '',
          isVisable: false,
          title: '',
        });
      });
    }
  }

  render() {
    const {
      dataList,
      total,
      pageSize,
      pageNum,
      dataMsg,
      boxtype,
      isVisable,
    } = this.state;
    const Permissiontype = [
      {
        value: '1',
        name: '数据源',
      },
      {
        value: '2',
        name: 'API',
      },
    ];
    const ApprovalStatus = [
      {
        value: '',
        name: '全部',
      },
      {
        value: '0',
        name: '待审批',
      },
      {
        value: '1',
        name: '同意',
      },
      {
        value: '2',
        name: '拒绝',
      },
    ];
    const statusList = [
      {
        value: '0',
        name: '待审批',
      },
      {
        value: '1',
        name: '同意',
      },
      {
        value: '2',
        name: '拒绝',
      },
    ];
    const columns = [
      { title: '申请账号', width: 100, dataIndex: 'applyUserName' },
      {
        title: '申请权限类型',
        width: 200,
        dataIndex: 'businessType',
        render: text => {
          return (
            <Space>
              <span>
                {Permissiontype.filter(item => item.value == text)[0].name}
              </span>
            </Space>
          );
        },
      },
      { title: '申请权限名称', width: 200, dataIndex: 'name' },
      {
        title: '权限有效期',

        render: render => {
          return (
            <Space>
              <span>
                {moment(render.startTime).format('YYYY-MM-DD') +
                  ' 至 ' +
                  moment(render.endTime).format('YYYY-MM-DD')}
              </span>
            </Space>
          );
        },
      },
      {
        title: '申请时间',
        dataIndex: 'applyTime',
        render: text => {
          return <span>{moment(text).format('YYYY-MM-DD HH:mm:ss')}</span>;
        },
      },
      {
        title: '状态',
        width: 100,
        dataIndex: 'status',
        render: text => {
          return (
            <Space>
              <span>
                {statusList.filter(item => item.value == text)[0].name}
              </span>
            </Space>
          );
        },
      },
      {
        title: '操作',
        width: 150,
        fixed: 'right',
        render: render => {
          return (
            <Space size="middle">
              <Button
                style={{
                  padding: 0,
                }}
                type="link"
                onClick={() => {
                  console.log('查看', render);
                  const { id, businessType } = render;
                  APIDetail({ id: id }).then(res => {
                    if (res.code == 'SUCCESS') {
                      if (businessType == 2) {
                        this.setState({
                          boxtype: 'check',
                          isVisable: true,
                          dataMsg: res.data,
                          title: 'API权限申请',
                          boxType: 2,
                        });
                      }
                      if (businessType == 1) {
                        this.setState({
                          boxtype: 'check',
                          isVisable: true,
                          dataMsg: res.data,
                          title: '数据源权限申请',
                          boxType: 1,
                        });
                      }
                    }
                  });
                }}
              >
                查看
              </Button>
              <Button
                style={{
                  padding: 0,
                }}
                type="link"
                disabled={render.status !== 0}
                onClick={() => {
                  if (!authorityVerify('APPROVAL_AUTHORITY')) return;
                  console.log('审批', render);
                  console.log('查看', render);
                  const { id, businessType } = render;
                  APIDetail({ id: id }).then(res => {
                    if (res.code == 'SUCCESS') {
                      if (businessType == 2) {
                        this.setState({
                          boxtype: 'approve',
                          isVisable: true,
                          dataMsg: res.data,
                          title: 'API审批',
                          boxType: 2,
                        });
                      }
                      if (businessType == 1) {
                        this.setState({
                          boxtype: 'approve',
                          isVisable: true,
                          dataMsg: res.data,
                          title: '数据源审批',
                          boxType: 1,
                        });
                      }
                    }
                  });
                }}
              >
                审批
              </Button>
              <Button
                style={{ padding: 0 }}
                type="link"
                onClick={() => {
                  if (!authorityVerify('APPROVAL_AUTHORITY')) return;
                  this.deleteUser(render.id);
                }}
              >
                删除
              </Button>
            </Space>
          );
        },
      },
    ];

    return (
      <div className={styles.TableContain}>
        <div className={styles.FormTable}>
          <Form layout={'inline'}>
            <Form.Item label="申请权限类型" colon={false}>
              <Select
                allowClear={true}
                placeholder="请选择"
                style={{
                  width: '197px',
                }}
                onChange={e => {
                  console.log(e, 777777777);
                  this.setState({
                    businessType: e,
                  });
                  this.searchChangeEvent?.next({});
                }}
              >
                {Permissiontype.map(item => {
                  return <Option value={item.value}>{item.name}</Option>;
                })}
              </Select>
            </Form.Item>
            <Form.Item label="审批状态" colon={false}>
              <Select
                allowClear={true}
                placeholder="请选择"
                style={{
                  width: '197px',
                }}
                onChange={e => {
                  console.log(e, 777777777);
                  this.setState({
                    status: e,
                  });
                  this.searchChangeEvent?.next({});
                }}
              >
                {ApprovalStatus.map(item => {
                  return <Option value={item.value}>{item.name}</Option>;
                })}
              </Select>
            </Form.Item>
          </Form>
        </div>
        <div className={styles.TableList}>
          <div className={styles.total} style={{ left: '10px' }}>
            共{total}条记录 第 {pageNum} /
            {(() => {
              var num = parseInt(total / pageSize);
              if (total % pageSize != 0) num += 1;
              return num;
            })()}{' '}
            页
          </div>

          <Table
            columns={columns}
            dataSource={dataList}
            onChange={(pagination, filters, sorter) => {
              this.setState(
                {
                  pageNum: pagination.current,
                  pageSize: pagination.pageSize,
                },
                () => {
                  this.getList();
                },
              );
            }}
            pagination={{
              showSizeChanger: true,
              showQuickJumper: true,
              current: pageNum,
              pageSize: pageSize,
              total: total,
              onShowSizeChange: (current, pageSize) => {},
            }}
          />
        </div>
        <MsgBox
          data={{ ...this.state }}
          onClose={this.closeBox.bind(this)}
          onSubmit={this.onSubmit.bind(this)}
        />
      </div>
    );
  }
}
